package com.xzp.gkrpc.client;

import com.xzp.gkrpc.Peer;
import com.xzp.gkrpc.common.utils.ReflectionUtils;
import com.xzp.gkrpc.transprot.HttpTransportClient;
import com.xzp.gkrpc.transprot.TransportClient;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@Slf4j
public class RandomTransportSelector implements TransportSelector{
    /**
     * 存储所有已连接的HttpTransportClient
     */
    List<TransportClient> transportClients;

    public RandomTransportSelector() {
        this.transportClients = new ArrayList<TransportClient>();
    }

    /**
     * 客户端初始化，针对不同的peer（服务器地址）分别创建count个链接
     * @param peers 可以连接的server端点信息
     * @param count client与server之间建立多少个连接
     * @param clazz client实现class
     */
    @Override
    public synchronized void init(List<Peer> peers, int count, Class<? extends TransportClient> clazz) {
        // 保证count>=1
        count = Math.max(count, 1);
        for(Peer peer: peers){
            for(int i=0; i<count; i++){
                TransportClient instance = ReflectionUtils.newInstance(clazz);
                instance.connect(peer);
                transportClients.add(instance);
            }
            log.info("connect server: {}", peer);
        }
    }

    /**
     * 返回一个随机连接的client
     * @return
     */
    @Override
    public synchronized TransportClient select() {
        // 随机连接
        int i = new Random().nextInt(transportClients.size());
        return transportClients.remove(i);
    }

    /**
     * 连接使用完毕 归还连接
     * @param client
     */
    @Override
    public synchronized void release(TransportClient client) {
        // 将连接归还到池子里
        transportClients.add(client);
    }

    /**
     * 关闭所有连接
     */
    @Override
    public synchronized void close() {
        for(TransportClient client: transportClients){
            client.close();
        }
        transportClients.clear();
    }
}
